package com.ebeitech.doorapp.view.setting;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.ebeitech.doorapp.R;
import com.ebeitech.doorapp.application.EbeiApplication;
import com.ebeitech.doorapp.bean.Module;
import com.ebeitech.doorapp.constants.CommonConstants;
import com.ebeitech.doorapp.db.CommonDBHelper;
import com.ebeitech.doorapp.domain.User;
import com.ebeitech.doorapp.view.BaseActivity;
import com.ebeitech.doorapp.view.customviews.CircleImageView;
import com.ebeitech.library.constant.SPConstants;
import com.ebeitech.library.ui.CommonTitleBar;
import com.ebeitech.library.util.CommonUtil;
import com.ebeitech.library.util.SPManager;
import com.ebeitech.library.util.StringUtil;
import com.ebeitech.library.util.VersionUtil;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by alice on 2017/10/31.
 */
public class SettingActivity extends BaseActivity {

	@BindView(R.id.view_title)
	CommonTitleBar mTitleBarView;
	@BindView(R.id.view_portraits)
	CircleImageView viewPortraits;
	@BindView(R.id.tv_name)
	TextView tvName;
	@BindView(R.id.tv_range)
	TextView tvRange;
	@BindView(R.id.view_content)
	LinearLayout viewContent;

	private List<Module> mModules = new ArrayList<Module>();

	private Context mContext;
	private View.OnClickListener mClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			String name = v.getTag().toString();
			if ("数据导出".equals(name)) {
				onBackupClicked(v);
			} else if ("数据导入".equals(name)) {
				onImportClicked(v);
			} else if (getString(R.string.ebei_check_version).equals(name)) {
				onCheckVersionClick(v);
			} else if (getString(R.string.ebei_about).equals(name)) {
				startActivity(new Intent(mContext, AboutActivity.class));
			} else if (getString(R.string.ebei_setting_system).equals(name)) {
				startActivity(new Intent(mContext, SettingSystemActivity.class));
			} else if (getString(R.string.ebei_app_manage).equals(name)) {
				startActivity(new Intent(mContext, AppManageActivity.class));
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Intent intent = getIntent();
		if (savedInstanceState == null) {
			savedInstanceState = new Bundle();
		}
		if (intent != null) {
			savedInstanceState.putBoolean(SPConstants.IS_FIT_STATUS_BAR, intent.getBooleanExtra(SPConstants.IS_FIT_STATUS_BAR, true));
		}
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ebei_activity_setting);
		mContext = this;
		ButterKnife.bind(this);
		initView();
	}

	private void initView() {
		mTitleBarView.setBtnBackVisible(false);
		mModules.clear();
		Module module = null;
		module = new Module();
		module.setName(getString(R.string.ebei_app_manage));
		mModules.add(module);
		module = new Module();
		module.setName(getString(R.string.ebei_setting_system));
		mModules.add(module);
		module = new Module();
		module.setName(getString(R.string.ebei_about));
		mModules.add(module);

		if (CommonConstants.IS_VERSION_DEV) {
			module = new Module();
			module.setName("数据导入");
			module.setDrawable(R.drawable.ebei_btn_keyboard);
			mModules.add(module);
			module = new Module();
			module.setName("数据导出");
			module.setDrawable(R.drawable.ebei_btn_keyboard);
			mModules.add(module);
		}

		for (Module item : mModules) {
			View view = LayoutInflater.from(mContext).inflate(R.layout.ebei_view_list_title_item, null);
			view.findViewById(R.id.view_arrow).setVisibility(View.VISIBLE);
			TextView textView = (TextView) view.findViewById(R.id.tvName);
			textView.setText(item.getName());
			viewContent.addView(view);
			view.setTag(item.getName());
			view.setOnClickListener(mClickListener);
		}

		User user = EbeiApplication.getUser();
		String username = StringUtil.getDefaultString(user.getUserName());
		tvName.setText(username);
		String userPortraits = user.getUserAvatar();
		Glide.with(this).load(userPortraits).into(viewPortraits);
		tvRange.setText(StringUtil.getDefaultString(user.getProjectName()));
	}

	private void onCheckVersionClick(View v) {

	}

	private void onBackupClicked(View v) {
		new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected Boolean doInBackground(Void... params) {
				// TODO Auto-generated method stub
				return backupDatabase();
			}

			protected void onPostExecute(Boolean result) {
				if (result) {
					Toast.makeText(mContext, "导出成功", Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(mContext, "导出失败", Toast.LENGTH_SHORT).show();
				}
			};

		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	private boolean backupDatabase() {
		String databasePath = CommonUtil.getFile(mContext);
		File file = new File(databasePath);
		if (!file.isDirectory()) {
			file.mkdirs();
		}
		SimpleDateFormat sdf = new SimpleDateFormat("MMddHHmm", Locale.CHINA);
		String version = VersionUtil.getVersionName(mContext);
		version = version.replace(".", "_");
		String databaseName = "data_" + sdf.format(new Date()) + "_" + version + ".zip";
		databasePath += "/" + databaseName;

		try {
			String packageName = null;
			try {
				PackageInfo info = this.getPackageManager().getPackageInfo(this.getPackageName(), 0);
				packageName = info.packageName;
			} catch (PackageManager.NameNotFoundException e) {
				e.printStackTrace();
			}
			if (StringUtil.isStringNullOrEmpty(packageName)) {
				return false;
			}
			String userAccount = SPManager.getInstance(this).get(SPConstants.USER_ACCOUNT, "");
			File newDb = new File(databasePath);
			File oldDb = new File("/data/data/" + packageName + "/databases/" + userAccount + CommonDBHelper.DB_NAME_SUFFIX + ".db");
			if (newDb.exists()) {
				newDb.delete();
			}
			if (oldDb.exists()) {
				if (CommonConstants.IS_VERSION_DEV) {
					databasePath = CommonUtil.getExternalCacheFile(mContext) + "/" + userAccount + CommonDBHelper.DB_NAME_SUFFIX + ".db";
					newDb = new File(databasePath);
					InputStream streamFrom = new FileInputStream(oldDb);
					OutputStream streamTo = new FileOutputStream(newDb);
					byte buffer[] = new byte[1024];
					int len;
					while ((len = streamFrom.read(buffer)) > 0) {
						streamTo.write(buffer, 0, len);
					}
					streamFrom.close();
					streamTo.close();
					return true;
				}

				ZipFile zFile = new ZipFile(newDb);
				zFile.setFileNameCharset("UTF-8"); // 设置文件名编码，在UTF-8系统中需要设置

				ZipParameters parameters = new ZipParameters();
				parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
				parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
				parameters.setEncryptFiles(true);
				parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
				parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
				parameters.setPassword("Ebei_2015@tech");
				zFile.createZipFile(oldDb, parameters);
				return true;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	private void onImportClicked(View v) {
		new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected Boolean doInBackground(Void... params) {
				// TODO Auto-generated method stub
				String userAccount = SPManager.getInstance(mContext).get(SPConstants.USER_ACCOUNT, "");
				File tempfile = new File(CommonUtil.getExternalCacheFile(mContext));
				if(!tempfile.exists()){
					tempfile.mkdir();
				}
				File newDb = new File(tempfile.getPath() + "/" + userAccount + CommonDBHelper.DB_NAME_SUFFIX + ".db");
				if(!newDb.exists()){
					return false;
				}
				try {
					String packageName = null;
					try {
						PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0);
						packageName = info.packageName;
					} catch (PackageManager.NameNotFoundException e) {
						e.printStackTrace();
					}
					if (StringUtil.isStringNullOrEmpty(packageName)) {
						return false;
					}
					File oldDb = new File("/data/data/" + packageName + "/databases/" + userAccount + CommonDBHelper.DB_NAME_SUFFIX + ".db");
					try {
						if(oldDb.exists()){
							oldDb.delete();
						}
						oldDb.createNewFile();
						InputStream in = new FileInputStream(newDb);
						int size = in.available();
						byte buf[] = new byte[size];
						in.read(buf);
						in.close();
						FileOutputStream out = new FileOutputStream(oldDb);
						out.write(buf);
						out.close();
						return true;
					} catch (Exception e) {
						e.printStackTrace();
					}

				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return false;
			}

			protected void onPostExecute(Boolean result) {
				if (result) {
					Toast.makeText(mContext, "导入成功", Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(mContext, "导入失败", Toast.LENGTH_SHORT).show();
				}
			};

		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

}
